import { AfterViewInit, Component, Input, OnDestroy, OnChanges, SimpleChanges, ViewChild } from '@angular/core';

import { CommonService } from './../../../core/services/common.service';
import { ChartService } from './chart.service';

@Component({
    selector: 'op-chart',
    template: `<div #chart [style.height]="chartHeight"></div>`,
    providers: [ChartService]
})
export class ChartComponent implements AfterViewInit, OnChanges, OnDestroy {
    @Input() chartHeight?: string = '300px';
    @Input() options: object;
    @ViewChild('chart', {static: false}) private container;
    private chart: any;

    constructor(
        private chartService: ChartService,
        private commonService: CommonService
    ) { }

    ngOnChanges(changes: SimpleChanges): void {
        if (!this.commonService.isNullOrUndefined(this.chart) && !this.commonService.isNullOrUndefined(changes.options.currentValue)) {
            this.chartService.setOptions(this.chart, changes.options.currentValue);
        }
    }

    ngAfterViewInit(): void {
        this.chart = this.chartService.getChart(this.container.nativeElement);
        this.resize();
    }

    ngOnDestroy(): void {
        this.chartService.disposeChart(this.chart);
    }

    resize(): void {
        this.chartService.resize(this.chart);
    }
}